﻿using System;
using System.Reflection;

namespace ArienToolkits.ReflectionUnilities
{
    /// <summary>
    /// 反射帮助类
    /// </summary>
    public class ReflectionHelper
    {
        /// <summary>
        /// 获取类型对象
        /// </summary>
        /// <param name="typeAndAssName">类型名称或程序集名称</param>
        /// <returns></returns>
        public static Type GetType(string typeAndAssName)
        {
            string[] strArray = typeAndAssName.Split(new char[] { ',' });
            if (strArray.Length < 2)
            {
                return Type.GetType(typeAndAssName);
            }
            return GetType(strArray[0].Trim(), strArray[1].Trim());
        }

        /// <summary>
        /// 获取类型对象
        /// </summary>
        /// <param name="typeFullName">类型完全限定名</param>
        /// <param name="assemblyName">程序集名称</param>
        /// <returns></returns>
        public static Type GetType(string typeFullName, string assemblyName)
        {
            if (assemblyName == null)
            {
                return Type.GetType(typeFullName);
            }
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly assembly in assemblies)
            {
                if (assembly.FullName.Split(new char[] { ',' })[0].Trim() == assemblyName.Trim())
                {
                    return assembly.GetType(typeFullName);
                }
            }
            Assembly assembly2 = Assembly.Load(assemblyName);
            if (assembly2 != null)
            {
                return assembly2.GetType(typeFullName);
            }
            return null;
        }

        /// <summary>
        /// 获取当前变量的变量名 字符串
        /// 调用：GetVarName(()=>test.str1); 返回 "str1"
        /// </summary>
        /// <param name="exp">需要获取的成员表达式</param>
        /// <returns></returns>
        public static string GetFieldName(System.Linq.Expressions.Expression<Func<string>> exp)
        {
            return ((System.Linq.Expressions.MemberExpression)exp.Body).Member.Name;
        }
    }
}
